package com.clusterswisdom.horn.api.quartz;

import org.quartz.CronTrigger;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

import com.clusterswisdom.horn.api.ioc.api.ApiConfig;

public class ScheduleContext {

	private SchedulerFactory schedulerFactory = new StdSchedulerFactory();
	
	private static ScheduleContext context = new ScheduleContext();
	
	private Scheduler scheduler;
	
	public static ScheduleContext getContext() {
		return context;
	}
	
	public void startScheduler() {
		try {
			schedulerFactory.getScheduler().start();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}
	
	public void addTaskAction(ApiConfig config) {
		try {
			JobDataMap dataMap = new JobDataMap();
			dataMap.put(ScheduleJob.PARAM_CONFIG, config);
			
			JobDetail jobDetail = new JobDetail(config.getName(), config.getService().getService(), ScheduleJob.class);//任务名，任务组，任务执行类  
			jobDetail.setJobDataMap(dataMap);
			
			CronTrigger trigger = new CronTrigger(config.getName(), config.getService().getService());//触发器名,触发器组  
			trigger.setCronExpression(config.getCron());//触发器时间设定  
			
			scheduler.scheduleJob(jobDetail, trigger);  
		       
		} catch (Exception e) {
			e.printStackTrace();
			
		}
	}
	
	private ScheduleContext() {
		try {
			scheduler = schedulerFactory.getScheduler();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}
}
